﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using VPN.Manage;
using VPN.DataContext;

namespace VPNNew
{
    public partial class NewPO : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                gvProduct.DataSource = ProductManage.GetProductList();
                gvProduct.DataBind();
            }
        }

        protected void txtAccountName_TextChanged(object sender, EventArgs e)
        {
            CustomValidator1.Validate();
        }

        public override string PageCode
        {
            get { return "MyAccounts"; }
        }

        protected void btnBuy_Click(object sender, EventArgs e)
        {
            if (IsValid)
            {
                Product p = ProductManage.GetProductByID((Guid)gvProduct.DataKeys[gvProduct.SelectedIndex][0]);

                Account a = new Account()
                {
                    AccountName = txtAccountName.Text.Trim(),
                    Quota = p.Quota,
                    Status = (int)AccountStatus.Disabled,
                    UserName = Page.User.Identity.Name,
                    Type = p.ProductCode,
                    AccountID = Guid.NewGuid(),
                    AccountCID = string.Empty,
                };

                PO po = new PO()
                {
                    AccountID = a.AccountID,
                    CreateDate = DateTime.Now,
                    HasPaid = false,
                    OringinalPrice = p.Price,
                    PONumber = string.Format("{0}-{1}-{2}",
                      DateTime.Now.ToString("yyyyMMddHHmm")
                      , p.ProductCode
                      , Math.Abs(Guid.NewGuid().GetHashCode()).ToString().Substring(0, 6)
                      ),
                    ProductID = p.ProductID,
                    POID = Guid.NewGuid(),
                    UserName = Page.User.Identity.Name,
                };
                POManage.Create(a, po);
                Response.Redirect(string.Format("~/PODetail.aspx?POID={0}", po.POID));
            }
        }

        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = AccountManage.GetAccountByAccountName(txtAccountName.Text.Trim()) == null;
        }

        protected void CustomValidator2_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = gvProduct.SelectedIndex > -1;
        }
    }
}
